package com.github.sd4324530.fastweixin.api.extra;

import com.github.sd4324530.fastweixin.api.config.ApiConfig;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Vector;
import java.util.concurrent.ConcurrentHashMap;

/**
 * ConcurrentHashMap 实现的缓存
 */
public class ConcurrentHashMapTokenCache implements TokenCache {

    /**
     * 初始长度酌情修改 由于现在需求是单微信公众号所以两个足够
     */
    private final static ConcurrentHashMap<String, Token> CACHE = new ConcurrentHashMap<String, Token>(2);

    private final static Vector<ApiConfig> API_CACHE = new Vector<ApiConfig>(5);


    @Override
    public void put(Token token) {
        if (null == token) {
            return;
        }
        CACHE.put(token.getAppid() + token.getType().toString(), token);
    }

    @Override
    public Token get(String appid, TokenType type) {
        if (null == type || null == appid || 0 == appid.trim().length()) {
            return null;
        }
        return CACHE.get(appid + type.toString());
    }

    @Override
    public Collection<Token> getAll() {
        return new ArrayList<Token>(CACHE.values());
    }

    @Override
    public void addConfig(ApiConfig config) {
        API_CACHE.add(config);
        TokenService.initTokenAndTicket(config,this);
    }

    @Override
    public Collection<ApiConfig> getAllApi() {
        return new ArrayList<ApiConfig>(API_CACHE);
    }
}
